package com.jiangruan.javaproject.request;

import java.io.*;
import java.net.*;
import java.util.Map;
import java.util.Set;

/**
 * @author:liufukai
 * @email:1324963242@qq.com
 * @desc:该类用于封装提供网络请求的功能代码，用于发起网络请求，并将网络的数据进行返回
 * @datatime:2021/12/522:51
 */
public class HttpUtils {
    /**
     * 该函数由于实现get请求，并将请求的结果返回
     *
     * @param path 请求的资源路径
     * @return 请求的结果
     */
    public static String get(String path) {
        //url :http://api.xxxx?city =&name
        String line = "";//最开始空行
        String result = ""; //每次读取到以后都要累计起来的读取结果
        InputStream inputStream = null;
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;

        try {
            //union resource location 统一资源定位
            URL url = new URL(path);
            URLConnection con = url.openConnection();
            //进行连接
            con.connect();
            // con.getRequestProperty("statuscode");
            //接收数据
            inputStream = con.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            //字符流：按行读
            reader = new BufferedReader(inputStreamReader);
//            String line=reader.readLine();
//            while (line!=null){
//                reader.readLine();
//            }
            //con.setRequestProperty();
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭读取流
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * java原生代码实现post请求，并返回请求结果
     * @param path   请求的路径
     * @param header 请求头的信息
     * @param data   请求数据
     * @return 请求的结果
     */

    public static String post(String path, Map<String, String> header, byte[] data) {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //请求头设置
            // ContentType:application/json 请求属性
            //AuthorizationL:"Basic "+"xxx"
            //如何拿到所有map中的数据（如何获取map数据）
            //List:有序的可以使用for循环
            // set：无序的，增强for循环，迭代器
            // map：无序的，get(key)>keySet()  增强for循环遍历key

            if (!header.isEmpty()) {
                Set<String> keys = header.keySet();
                for (String key : keys
                ) {
                    String value = header.get(key);
                    conn.setRequestProperty(key, value);
                }
            }
            conn.connect();//进行连接

            //将请求数据发送出去服务端
            outputStream = conn.getOutputStream();
            outputStream.write(data);
            //读取响应的数据
            inputStream = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result = result + line;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
